package com.hospital.dictionary.module.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hospital.common.core.result.ErrorTip;
import com.hospital.common.core.result.SuccessTip;
import com.hospital.common.core.result.Tip;
import com.hospital.common.core.utils.StringUtil;
import com.hospital.dictionary.constant.CommonConstant;
import com.hospital.dictionary.module.entity.SysPermission;
import com.hospital.dictionary.module.entity.SysRole;
import com.hospital.dictionary.module.entity.vo.TreeModel;
import com.hospital.dictionary.module.service.SysPermissionService;
import com.hospital.dictionary.module.service.SysRoleService;
import com.hospital.dictionary.query.QueryGenerator;
import com.hospital.dictionary.utils.KitUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/module/role")
@Slf4j
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysPermissionService sysPermissionService;

    @GetMapping(value = "/list")
    public Tip queryPageList(SysRole role,
                             @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                             @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                             HttpServletRequest req) {
        QueryWrapper<SysRole> queryWrapper = QueryGenerator.initQueryWrapper(role, req.getParameterMap());
        Page<SysRole> page = new Page<>(pageNo, pageSize);
        IPage<SysRole> pageList = sysRoleService.page(page, queryWrapper);
        return new SuccessTip(pageList);
    }

    @PostMapping("/add")
    public Tip add(@RequestBody SysRole role){
        role.setCreateTime(new Date());
        boolean save = sysRoleService.save(role);
        return KitUtil.setResult(save,302,"操作失败","操作成功");
    }

    @PutMapping("/edit")
    public Tip edit(@RequestBody SysRole role){
        SysRole byId = sysRoleService.getById(role.getDictId());
        if(byId!=null){
            boolean b = sysRoleService.updateById(role);
            return KitUtil.setResult(b,302,"操作失败","操作成功");
        }
        return new ErrorTip(302,"未找到对应数据");
    }

    @DeleteMapping("/delete")
    public Tip delete(@RequestParam(name="id",required=true) String id){
        boolean b = sysRoleService.removeById(id);
        return KitUtil.setResult(b,302,"操作失败","操作成功");
    }

    @GetMapping("/queryAll")
    public Tip queryAll(){
        List<SysRole> list = sysRoleService.list();
        return KitUtil.setResult(list!=null,302,"未找到权限列表",list);
    }

    /**
     * 用户角色授权功能，查询菜单权限树
     * @param request
     * @return
     */
    @GetMapping(value = "/queryTreeList")
    public Tip queryTreeList(HttpServletRequest request) {
        //全部权限ids
        List<String> ids = new ArrayList<>();
        try {
            LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
            query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);
            query.orderByAsc(SysPermission::getSortNo);
            List<SysPermission> list = sysPermissionService.list(query);
            for(SysPermission sysPer : list) {
                ids.add(sysPer.getDictId());
            }
            List<TreeModel> treeList = new ArrayList<>();
            getTreeModelList(treeList, list, null);
            Map<String,Object> resMap = new HashMap<String,Object>();
            resMap.put("treeList", treeList); //全部树节点数据
            resMap.put("ids", ids);//全部树ids
            return new SuccessTip(resMap);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return new ErrorTip(302,"查询失败");
        }
    }

    private void getTreeModelList(List<TreeModel> treeList,List<SysPermission> metaList,TreeModel temp) {
        for (SysPermission permission : metaList) {
            String tempPid = permission.getParentId();
            TreeModel tree = new TreeModel(permission.getDictId(), tempPid, permission.getName(),permission.getRuleFlag(), permission.isLeaf());
            if(temp==null && StringUtil.isEmpty(tempPid)) {
                treeList.add(tree);
                if(!tree.getIsLeaf()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            }else if(temp!=null && tempPid!=null && tempPid.equals(temp.getKey())){
                temp.getChildren().add(tree);
                if(!tree.getIsLeaf()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            }
        }
    }


}
